<?php
namespace app\back\model;

use think\Model;
use think\Db;
use \app\common\validate\AccountMoney as AMValidate;
use think\Validate;
class AccountMoney extends Model
{
    protected $table = 'account_money';

    var $allowField = ['recharge_money', 'give_money'];
    var $timesAllowField = ['diy_times', 'fish_times', 'rollball_times'];
    var $error_message, $usepaycode;

	/*
	 * 充值
	 * 
	 */
    public function recharge()
    {   
        $this->allowField($this->allowField)->data($_POST);
        // 验证数据的合法性
        $account_money_validate = new AMValidate();
        $validate_res = $account_money_validate->scene('recharge')->check($this->getData());

        if(false === $validate_res){
            $this->error_message = $account_money_validate->getError();
            return false;
        }

        $record_model = model('AccountRecord');
        $queue_model = model('WeixinQueue');
        // 开启事务进行充值与日志写入
        Db::startTrans();
        try{
            // 写入金额表
            $this->amount_money = $this->recharge_money+$this->give_money;

            // 定义金额数据内容
            $incField = [
                'amount_money'=>['exp', 'amount_money' . '+' . $this->amount_money],
                'recharge_money'=>['exp', 'recharge_money' . '+' . $this->recharge_money],
            ];

            // 记录充值
            $record_data[] = [
                'mobile'=>$this->mobile,
                'money'=>$this->recharge_money,
                'recharge_type'=>AccountRecord::RECHARGE_TYPE,
                'message'=>$record_model->getRechargeTypeAttr(AccountRecord::RECHARGE_TYPE).$this->recharge_money.'元'];

            if($this->give_money > 0) {
                // 赠送记录
                $record_data[] = [
                    'mobile'=>$this->mobile,
                    'money'=>$this->give_money,
                    'recharge_type'=>AccountRecord::GIVE_TYPE,
                    'message'=>$record_model->getRechargeTypeAttr(AccountRecord::GIVE_TYPE).$this->give_money.'元'];

                // 赠送金额自增
                $incField['give_money'] = ['exp', 'give_money' . '+' . $this->give_money];
            }

            // 修改金额
            db($this->table)->where(['mobile'=>$this->mobile])->setField($incField);

            // 记录保存入库
            $record_model->saveAll($record_data);

            $queue_model->wexinRechargeQueue($this->mobile, $this->recharge_money, ($this->give_money?$this->give_money:0));

            Account::where('mobile', $this->mobile)->where('level', '<', '1')->update(['level' => '1']);

            // 提交事务
            Db::commit();
            return true;
       } catch (\Exception $e) {
           // 回滚事务
           Db::rollback();
           $this->error_message = $e->getMessage();
           return false;
       }
    }

    /*
     * 次数充值逻辑
     */
    function timesRecharge() {
        // 过滤掉干扰字段
        $this->allowField($this->timesAllowField)->data($_POST);

        // 验证数据的合法性
        $account_money_validate = new AMValidate();
        $validate_res = $account_money_validate->scene('times_recharge')->check($this->getData());

        if(false === $validate_res){
            $this->error_message = $account_money_validate->getError();
            return false;
        }

        $record_model = model('AccountRecord');
        $queue_model = model('WeixinQueue');
        // 开启事务进行充值与日志写入
        Db::startTrans();
        try{

            // 定义金额数据内容
            $incField = [
                'fish_times'=>['exp', 'fish_times' . '+' . intval($this->fish_times)],
                'diy_times'=>['exp', 'diy_times' . '+' . intval($this->diy_times)],
                'rollball_times'=>['exp', 'rollball_times' . '+' . intval($this->rollball_times)],
            ];

            if(input('?post.deduction')){
                $incField['amount_money'] = ['exp', 'amount_money' . '-' . $this->deduction_money];
                $incField['recharge_money'] = ['exp', 'recharge_money' . '-' . $this->deduction_money];

                $record_data[] = [
                'mobile'=>$this->mobile,
                'money'=>$this->deduction_money,
                'recharge_type'=>AccountRecord::TIMES_RECHARGE_DE_TYPE,
                'message'=>$record_model->getRechargeTypeAttr(AccountRecord::TIMES_RECHARGE_DE_TYPE).$this->deduction_money.'元'];
            }

            // 记录充值
            $record_data[] = [
                'mobile'=>$this->mobile,
                'money'=>$this->recharge_money,
                'recharge_type'=>AccountRecord::TIMES_RECHARGE_TYPE,
                'message'=>$record_model->getRechargeTypeAttr(AccountRecord::TIMES_RECHARGE_TYPE).$this->recharge_money.'元'];

            // 修改金额
            db($this->table)->where(['mobile'=>$this->mobile])->setField($incField);

            // // 记录保存入库
            $record_model->saveAll($record_data);

            $queue_model->wexinTimesRechargeQueue($this->mobile, ($this->diy_times+$this->rollball_times+$this->fish_times));

            Account::where('mobile', $this->mobile)->where('level', '<', '2')->update(['level' => '2']);

            // 提交事务
            Db::commit();
            
            return true;
       } catch (\Exception $e) {
           // 回滚事务
           Db::rollback();
           $this->error_message = $e->getMessage();
           return false;
       } 
    }

    /*
     * 消费逻辑
     */
    public function consumption() {
        // 验证数据的合法性
        $account_money_validate = new AMValidate();
        $validate_res = $account_money_validate->scene('consumption')->check($this->getData());

        if(false === $validate_res){
            $this->error_message = $account_money_validate->getError();
            return false;
        }
        
        // 获取消费数据
        $consumption_data = $this->getConsumptionData();
        // 结果有误，返回
        if($consumption_data ===  false) {
            return false;
        }

        $record_model = model('AccountRecord');
        $queue_model = model('WeixinQueue');
        // 赋值记录数据
        $record_data['mobile'] = $this->mobile;
        $record_data['money'] = $this->consumption_money;
        $record_data['recharge_type'] = $record_model::CONSUMPTION_TYPE;
        $record_data['message'] = $consumption_data['record_message'];
        $record_data['consume_by_friend'] = isset($this->consumption_self) ? 0 : 1;

        // 开启事务进行充值与日志写入
        Db::startTrans();
        try {
            // 保存数据
            $consumption_data['obj']->data($consumption_data['data'])->save();
            $record_model->save($record_data);

            $queue_model->wexinConsumptionQueue($this->mobile, $this->consumption_money, $this->diy_times, $this->fish_times, $this->rollball_times);

            Db::commit();
            return true;
        } catch(\Exception $e) {
            // 回滚事务
           Db::rollback();
           $this->error_message = $e->getMessage();
           return false;
        }
    }

    // 获取充值参数
    protected function getConsumptionData() {
        $userinfo = self::get(['mobile'=>$this->mobile]);

        if(!$userinfo) {
            $this->error_message = '会员查询有误，请重试';
            return false;
        }

        $amount_money = $userinfo->amount_money;
        $recharge_money = $userinfo->recharge_money;
        $give_money = $userinfo->give_money;

        // 判断余额是否足够
        if($amount_money < $this->consumption_money) {
            $this->error_message = '余额不足';
            return false;
        }

        $record_message = '';
        
        if($this->diy_times > 0 && $userinfo->diy_times < $this->diy_times) {
            $this->error_message = '【DIY乐园】次数不足';
            return false;
        } else if($this->diy_times > 0) {
            $consumption_data['diy_times'] = ['exp', 'diy_times-'.$this->diy_times];
            $record_message .= '扣除DIY乐园'.$this->diy_times.'次;';
        }

        if($this->fish_times > 0 && $userinfo->fish_times < $this->fish_times) {
            $this->error_message = '【吃奶鱼】次数不足';
            return false;
        } else if($this->fish_times > 0) {
            $consumption_data['fish_times'] = ['exp', 'fish_times-'.$this->fish_times];
            $record_message .= '扣除吃奶鱼'.$this->diy_times.'次;';
        }

        if($this->rollball_times > 0 && $userinfo->rollball_times < $this->rollball_times) {
            $this->error_message = '【动物滚球】次数不足';
            return false;
        } else if($this->rollball_times > 0) {
            $consumption_data['rollball_times'] = ['exp', 'rollball_times-'.$this->rollball_times];
            $record_message .= '扣除动物滚球'.$this->diy_times.'次;';
        }

        // 余额
        $consumption_data['amount_money'] = $amount_money-$this->consumption_money;
        $consumption_data['last_consumption_time'] = date('Y-m-d H:i:s');

        // 判断消费优先顺序
        if(isset($this->give_first) && $this->consumption_money > 0) {
            if($give_money >= $this->consumption_money){
                $consumption_data['give_money'] = $give_money-$this->consumption_money;
                $record_message .= "扣除赠送金额：{$this->consumption_money}元;";
            }else {
                $consumption_data['give_money'] = 0;
                $consumption_data['recharge_money'] = $recharge_money + ($give_money-$this->consumption_money);
                $record_message = "扣除赠送金额：{$give_money}元";
                $record_message .= "充值金额：".($this->consumption_money-$give_money)."元;";
                $record_message .= "总计扣除{$this->consumption_money}元";
            }
        } else if($this->consumption_money > 0){
            if($recharge_money >= $this->consumption_money){
                $consumption_data['recharge_money'] = $recharge_money-$this->consumption_money;
                $record_message = "扣除充值金额：{$this->consumption_money}元";
            }else {
                $consumption_data['recharge_money'] = 0;
                $consumption_data['give_money'] = $give_money + ($recharge_money-$this->consumption_money);
                $record_message = "扣除充值金额：{$recharge_money}元;";
                $record_message .= "扣除赠送金额：".($this->consumption_money-$recharge_money)."元;";
                $record_message .= "总计扣除{$this->consumption_money}元";
            }
        }

        return ['data' =>$consumption_data, 'obj'=>$userinfo, 'record_message'=>$record_message];
    }

    /*
     * 新会员注册福利
     * $from 注册来源， worder|weixin
     */
    function newCustomerWelfare($mobile='', $money=0, $from='worker') {
        // 判断是否有会注册会员活动
        if(!newuser_ticket()) 
            return false;

        if(empty($mobile)) {
            $this->error_message = '缺少手机信息';
            return false;
        }

        if(!$this->where('mobile', $mobile)->count()) {
            $this->error_message = '未查到相关帐号';
            return false;
        }

        $record_model = new AccountRecord;
        Db::startTrans();
        try {
            // 保存数据
            // 定义金额数据内容
            $incField = [
                'amount_money'=>['exp', 'amount_money' . '+' . $money],
                'give_money'=>['exp', 'give_money' . '+' . $money],
            ];
            // 计入帐户金额
            db($this->table)->where(['mobile'=>$mobile])->setField($incField);

            // 记录赠送金额
            $record_data = [
                    'mobile'=>$mobile,
                    'money'=>$money,
                    'recharge_type'=>AccountRecord::SYSTEM_TYPE,
                    'message'=>$record_model->getRechargeTypeAttr(AccountRecord::SYSTEM_TYPE).$money.'元',
            ];
            $record_model->save($record_data);

            Db::commit();
        } catch(\Exception $e) {
            // 回滚事务
           Db::rollback();
           $this->error_message = $e->getMessage();
           return false;
        }

        return true;
    }

    /*
     * 管理员修改用户信息
     */
    function AMoneyEdit() {

        $record_data['origin_data'] = $this->data;

        $this->allowField(['recharge_money','give_money', 'diy_times', 'fish_times', 'rollball_times'])->data($_POST);

        $rule = [
            'mobile'  =>  'require|regex:/^1[3-9]\d{9}$/|token',
            'recharge_money'  =>  'require|egt:0|float',
            'give_money'  =>  'require|float|egt:0',
            'diy_times'  => 'require|number|egt:0',
            'fish_times'  => 'require|number|egt:0',
            'rollball_times'  => 'require|number|egt:0',
        ];

        $validate = new Validate($rule);
        $validate_res = $validate->check($this->getData());

        if(false === $validate_res){
            $this->error_message = $validate->getError();
            return false;
        }

        $record_data['new_data'] = $this->getData();
        $record_data['change_data'] = $this->getChangedData();

        $record_model = new AccountRecord;
        $queue_model = model('WeixinQueue');

        Db::startTrans();
        try {
            $this->save();
            $this::where('mobile', $this->mobile)->update(['amount_money'=>['exp', 'recharge_money+give_money']]);

             // 记录赠送金额
            $record_data = [
                    'mobile'=>$this->mobile,
                    'money'=>0,
                    'recharge_type'=>AccountRecord::SYSTEM_EDIT,
                    'message'=>json_encode($record_data, JSON_UNESCAPED_UNICODE),
            ];
            $record_model->save($record_data);

            // 记录微信通知队列
            $queue_model->editKefuNotice($this->mobile, $record_model->id);

            Db::commit();

            return true;
        } catch(\Exception $e) {
            // 回滚事务
           Db::rollback();
           $this->error_message = $e->getMessage();
           return false;
        }
        
    }
}
